//
//  ALLoginPlugin.m
//  Runner
//
//  Created by mac on 2021/9/24.
//

#import "ALLoginPlugin.h"
//#import "PNSMainController.h"
//#import "PNSBaseNavigationController.h"
#import <ATAuthSDK/ATAuthSDK.h>


@interface ALLoginPlugin ()

@property (nonatomic, assign) BOOL isCanUseOneKeyLogin;
@property (nonatomic, strong) UIViewController *controller;
@end
//通道名称
static NSString *const CHANNEL_NAME = @"com.ahj/LoginPlugin";
//通道方法
static NSString *const CHANNEL_METHOD = @"yijiandenglu";
// 高德地图 key
static NSString *const PNSATAUTHSDKINFO = @"92iwwPWRbovYinN6BaOG/yeZGcCtQz0nlFrniCPai3R4t4fn34CzO4MpIY++yHCiLbMY+2SxDyqlEGFhbM4dJfiId9QZfAEmyFUtxGcmSWZtwhoKQ7JIvzPHIxLnQ6UvPwY/QAOsCG0Z3DOBfeMGKirssnhJFaM4o7BEXs7ERowaJobcwkCgb9x4zpti3glb8Um0u/QCQGraL3kuSLMQzMm1dWCspdln5KB1BW8BuXK/S65hZTWrstGJZZ+RxQx8+0gdNnqzXJY=";

@implementation ALLoginPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {

  FlutterMethodChannel* channel = [FlutterMethodChannel
      methodChannelWithName:CHANNEL_NAME
            binaryMessenger:[registrar messenger]];


    UIViewController *viewController = [UIApplication sharedApplication].delegate.window.rootViewController;

    ALLoginPlugin *plugin = [[ALLoginPlugin alloc]initWithViewController:viewController];

  [registrar addMethodCallDelegate:plugin channel:channel];

}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
  if ([CHANNEL_METHOD isEqualToString:call.method]) {
      [self kInitLocationInfo:call result:result];
  } else {
    result(FlutterMethodNotImplemented);
  }
}
// MAKE: 初始化
- (void)kInitLocationInfo:(FlutterMethodCall*)call result:(FlutterResult)result{

    /**
     *  设置 ATAuthSDK 的秘钥信息
     *  建议该信息维护在自己服务器端
     *  放在程序入口处调用效果最佳
     *
     *  1. 首先会从本地沙盒中找
     *  2. 沙盒找不到使用本地最初的秘钥进行初始化
     *  3. 同时发送异步请求从服务端拉取最新秘钥，拉取成功更新到本地沙盒中
     */
//    NSString *authSDKInfo = [[NSUserDefaults standardUserDefaults] objectForKey:PNSATAUTHSDKINFOKEY];
//    if (!authSDKInfo || authSDKInfo.length == 0) {
//        authSDKInfo = PNSATAUTHSDKINFO;
//    }
//    [PNSHttpsManager requestATAuthSDKInfo:^(BOOL isSuccess, NSString * _Nonnull authSDKInfo) {
//        if (isSuccess) {
//            [[NSUserDefaults standardUserDefaults] setObject:authSDKInfo forKey:PNSATAUTHSDKINFOKEY];
//        }
//    }];

    [[TXCommonHandler sharedInstance] setAuthSDKInfo:PNSATAUTHSDKINFO
                                            complete:^(NSDictionary * _Nonnull resultDic) {
        NSLog(@"设置秘钥结果：%@", resultDic);
    }];

    [self checkAndPrepareEnv:result];



}

#pragma mark - Logic
- (void)checkAndPrepareEnv:(FlutterResult)result{
    //开始状态置为YES，默认当前环境可以使用一键登录
    self.isCanUseOneKeyLogin = YES;

    __weak typeof(self) weakSelf = self;
    //环境检查，异步返回
    [[TXCommonHandler sharedInstance] checkEnvAvailableWithAuthType:PNSAuthTypeLoginToken
                                                           complete:^(NSDictionary * _Nullable resultDic) {
        NSLog(@"环境检查返回：%@", resultDic);
        weakSelf.isCanUseOneKeyLogin = [PNSCodeSuccess isEqualToString:[resultDic objectForKey:@"resultCode"]];

        if (weakSelf.isCanUseOneKeyLogin == YES) {
            [[TXCommonHandler sharedInstance] accelerateLoginPageWithTimeout:3.0 complete:^(NSDictionary * _Nonnull resultDic) {
                NSLog(@"为后面授权页拉起加个速，加速结果：%@", resultDic);


            }];


        }
        /// 拉起一键登录页面
        [weakSelf clickoneKeyLogin:result];
    }];
}

#pragma mark - Action
- (void)clickoneKeyLogin:(FlutterResult)result{
    if (self.isCanUseOneKeyLogin == NO) {
//        [self kAlertAction:@"当前环境不支持一键登录"];
        result(@"-100");
    } else {


        TXCustomModel *model = [[TXCustomModel alloc] init];
        model.changeBtnIsHidden = YES;
        [[TXCommonHandler sharedInstance] getLoginTokenWithTimeout:3.0
                                                        controller:self.controller
                                                             model:model
                                                          complete:^(NSDictionary * _Nonnull resultDic) {
            NSString *resultCode = [resultDic objectForKey:@"resultCode"];
            if ([PNSCodeLoginControllerPresentSuccess isEqualToString:resultCode]) {
                NSLog(@"授权页拉起成功回调：%@", resultDic);

            } else if ([PNSCodeLoginControllerClickCancel isEqualToString:resultCode] ||
                       [PNSCodeLoginControllerClickChangeBtn isEqualToString:resultCode] ||
                       [PNSCodeLoginControllerClickLoginBtn isEqualToString:resultCode] ||
                       [PNSCodeLoginControllerClickCheckBoxBtn isEqualToString:resultCode] ||
                       [PNSCodeLoginControllerClickProtocol isEqualToString:resultCode]) {
                NSLog(@"页面点击事件回调：%@", resultDic);
            } else if ([PNSCodeSuccess isEqualToString:resultCode]) {
                NSLog(@"获取LoginToken成功回调：%@", resultDic);
                NSString *token = [resultDic objectForKey:@"token"];

                NSLog(@"获取LoginToken：%@", token);

                result(token);

                NSLog(@"接下来可以拿着Token去服务端换取手机号，有了手机号就可以登录，SDK提供服务到此结束");
                [[TXCommonHandler sharedInstance] cancelLoginVCAnimated:YES complete:nil];
            } else {
                result(@"-100");
                NSLog(@"获取LoginToken或拉起授权页失败回调：%@", resultDic);

            }
        }];
    }
}

- (instancetype)initWithViewController:(UIViewController *)viewController {
    self = [super init];
    if (self) {
        self.controller = viewController;
    }
    return self;
}
- (void)kAlertAction :(NSString *)message{

    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];

    [alertVC addAction:confirmAction];

    [self.controller presentViewController:alertVC animated:YES completion:nil];

}

@end
